package com.fifth.apartment.service.impl;

import com.fifth.apartment.common.SMScommon;
import com.fifth.apartment.result.Result;
import com.fifth.apartment.service.UserLoginService;
import com.fifth.apartment.utils.RandomUtil;
import com.fifth.apartment.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @author Dao
 * @since 2024/7/14
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result sendCode(String phone) {
        if (StringUtils.hasLength(phone)){
            if(stringRedisTemplate.opsForValue().get(phone+"_"+ SMScommon.SMS_CODE_LOGIN)!=null){
                return new Result(false,"一分钟以内不能获取验证码");
            }


            String code = RandomUtil.getSixBitRandom();

            //TODO 阿里云短信验证码发送
            stringRedisTemplate.opsForValue().set(phone+"_"+ SMScommon.SMS_CODE_LOGIN,code,1, TimeUnit.MINUTES);

            stringRedisTemplate.opsForValue().set(phone+"_"+SMScommon.SMS_CODE_LOGIN+"_"+code,code,5,TimeUnit.MINUTES);

            return new Result(true,"发送验证码成功",code);
        }
        return new Result(false,"发送验证码失败");
    }

    @Override
    public Result login(LoginVO vo) {
        if (ObjectUtils.isEmpty(vo)){
            return new Result(false,"登录失败");
        }

        String phone = vo.getPhone();
        String code =vo.getCode();

        String codeInRedis = stringRedisTemplate.opsForValue().get(phone + "_" + SMScommon.SMS_CODE_LOGIN + "_" + code);
        if (StringUtils.hasLength(phone) && StringUtils.hasLength(code)){
            if (StringUtils.hasLength(codeInRedis)&&code.equals(codeInRedis)){

                //TODO  JWT令牌
                return new Result(true,"登录成功");
            }
            return new Result(false,"登录失败");
        }

        return new Result(false,"登录失败");
    }
}
